"""
FileName：database_manager.py
Description：
Author：gaojiahui
Time：2025/8/15 15:05
Website：https://gitee.com/gao-jiahui
"""
import logging

import pymysql
from pymysql.cursors import DictCursor

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("DB_Validator")

"""数据库连接与查询"""
class DatabaseManager:
    def __init__(self, host, port, user, password, database):
       self.connection = pymysql.connect(
           host=host,
           port=port,
           user=user,
           password=password,
           database=database,
           charset='utf8mb4',
           cursorclass=DictCursor
       )

    def execute_query(self,sql,params=None):
        """执行查询语句"""
        try:
            with self.connection.cursor() as cursor:
                cursor.execute(sql,params or ())
                return cursor.fetchall()
        except pymysql.Error as e:
            logger.error(f"数据库查询失败:{e}")
            raise

    def execute_update(self,sql,params=None):
        """执行更新语句"""
        try:
            with self.connection.cursor() as cursor:
                affected_rows = cursor.execute(sql,params or ())
                self.connection.commit()
                return affected_rows
        except pymysql.Error as e:
            self.connection.rollback()
            logger.error(f"数据库更新失败:{e}")
            raise

    def close(self):
        """关闭数据库连接"""
        if self.connection:
            self.connection.close()
            logger.info("数据库连接已关闭")

# 使用示例
db = DatabaseManager(
    host="localhost",
    port=3306,
    user="root",
    password="root",
    database="pig"
)

# 查询订单数据
order = db.execute_query(
    "SELECT * FROM pig_order WHERE order_id = %s",
    (1001,)
)[0]

print(f"订单状态:{order['status']}")
print(f"创建时间:{order['create_time']}")

# 更新订单状态
db.execute_update(
    "UPDATE pig_order SET status = 'COMPLETED' WHERE order_id = %s",
    (1001,)
)

db.close()